//
//  Tools.m
//  iCarCenter
//
//  Created by Storm on 14-4-28.
//  Copyright (c) 2014年 Storm. All rights reserved.
//

#import "Tools.h"
#import "NSDate+Addition.h"
@implementation Tools

// 从字符串中获取字数个数为N的字符串，单字节字符占半个字数，双字节占一个字数
+ (NSString *)getSubString:(NSString *)strSource WithCharCounts:(NSInteger)number
{
    // 一个字符以内，不处理
	if (strSource == nil || [strSource length] <= 1) {
		return strSource;
	}
	char *pchSource = (char *)[strSource cStringUsingEncoding:NSUTF8StringEncoding];
	int sourcelen = (int)strlen(pchSource);
	int nCharIndex = 0;		// 字符串中字符个数,取值范围[0, [strSource length]]
	int nCurNum = 0;		// 当前已经统计的字数
	for (int n = 0; n < sourcelen; ) {
		if( *pchSource & 0x80 ) {
			if ((nCurNum + 2) > number * 2) {
				break;
			}
			pchSource += 3;		// NSUTF8StringEncoding编码汉字占３字节
			n += 3;
			nCurNum += 2;
		}
		else {
			if ((nCurNum + 1) > number * 2) {
				break;
			}
			pchSource++;
			n += 1;
			nCurNum += 1;
		}
		nCharIndex++;
	}
	assert(nCharIndex > 0);
	return [strSource substringToIndex:nCharIndex];
}

+(NSString *) getStringFromArray:(NSArray *)srcArray byCharacter:(NSString *)character
{
	NSMutableString *mutabString = [[NSMutableString alloc] init];
	int i = 0;
	if (srcArray.count > 0)
	{
		for (i = 0; i < srcArray.count-1; i++)
		{
			[mutabString appendFormat:@"%@%@",[srcArray objectAtIndex:i],character];
		}
		[mutabString appendString:[srcArray objectAtIndex:i]];
	}
	return mutabString;
}


+(NSString*)timestamp:(NSString*)dateTimeStr lastDateTimeStr:(NSString *)lastDateTime
{
    //将传入时间转化成需要的格式
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate = [format dateFromString:dateTimeStr];
    NSDate *lfromdate = [format dateFromString:lastDateTime];
    
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSInteger lfrominterval = [fromzone secondsFromGMTForDate:lfromdate];
    
    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    NSDate *localeDate = [lfromdate  dateByAddingTimeInterval: lfrominterval];
    
    double intervalTime = [localeDate timeIntervalSinceReferenceDate] - [fromDate timeIntervalSinceReferenceDate];
    
    long lTime = (long)intervalTime;
    NSInteger iSeconds = lTime % 60;
    NSInteger iMinutes = (lTime / 60) % 60;
    NSInteger iHours = (lTime / 3600);
    NSInteger iDays = lTime/60/60/24;
    NSInteger iMonth = lTime/60/60/24/12;
    NSInteger iYears = lTime/60/60/24/384;
    
    // NSLog(@"相差%d年%d月 %d日%d时%d分%d秒", iYears,iMonth,iDays,iHours,iMinutes,iSeconds);
    
    if(iYears>0){
        
        return [NSString stringWithFormat:@"%ld年前",iYears];
        
    }else if(iMonth>0){
        return [NSString stringWithFormat:@"%ld个月前",iMonth];
    }else if(iDays>=7){
        if (iDays ==7) {
            return @"1周前";
        }
        return [NSString  stringWithFormat:@"%ld周前",iDays/7];
    }else if(iDays>0){
        return [NSString  stringWithFormat:@"%ld天前",iDays];
    }else if(iHours>0){
        return [NSString  stringWithFormat:@"%ld小时前",iHours];
    }else if(iMinutes>0){
        return [NSString  stringWithFormat:@"%ld分钟前",iMinutes];
    }else if(iSeconds > 0){
        return [NSString  stringWithFormat:@"%ld秒前",iSeconds];
    }else {
        return @"刚刚";
    }
    
    return nil;
}
+(NSString*)getDaysFromDates:(NSString*)dateTimeStr lastDateTimeStr:(NSString *)lastDateTime{
    //将传入时间转化成需要的格式
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *fromdate = [format dateFromString:dateTimeStr];
    NSDate *lfromdate = [format dateFromString:lastDateTime];
    
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSInteger lfrominterval = [fromzone secondsFromGMTForDate:lfromdate];
    
    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    NSDate *localeDate = [lfromdate  dateByAddingTimeInterval: lfrominterval];
    
    double intervalTime = [localeDate timeIntervalSinceReferenceDate] - [fromDate timeIntervalSinceReferenceDate];
    
    long lTime = (long)intervalTime;
    NSInteger iDays = lTime/60/60/24;
    
    if(iDays>0){
        return [NSString  stringWithFormat:@"%ld",iDays];
    }
    return nil;

}
+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}

//计算 中英文混合 字符数；
+(int)convertToInt:(NSString*)strtemp {
	
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return strlength;
	
}


//图片压缩
+(NSData *) scaleImage:(UIImage *) image
{
	NSData *dataImage = UIImageJPEGRepresentation(image, 1.0);
	NSLog(@"imagesize:%ld",dataImage.length/1024);
    NSUInteger sizeOrigin = [dataImage length];
    NSUInteger sizesizeOriginKB = sizeOrigin / 1024;
	
	
	float q = 1.0;
	if (sizesizeOriginKB > 1024*10) //10M
	{
		q = 0.5;
	}else if(sizesizeOriginKB > 1024*7) //7M
	{
		q = 0.7;
	}
	else if(sizesizeOriginKB > 1024*5) //5M
	{
		q = 0.8;
	}else if(sizesizeOriginKB > 1024*4){
        q = 0.9;
    }
	else if(sizesizeOriginKB > 1024*3)//3M
	{
		q = 0.92;
	}
    //	else if(sizesizeOriginKB > 1024) //1M
    //	{
    //		q = 0.9;
    //	}
    
    // 图片压缩
    if (q !=1.0)
	{
		NSLog(@"q:%f",q);
        CGSize sizeImage = [image size];
        NSLog(@"before !!!!,%@,%f,%f",image,sizeImage.width,sizeImage.height);
        CGFloat iwidthSmall = sizeImage.width * q;
		CGFloat iheightSmall = sizeImage.height * q;
		
		//为了保证在主页的显示，宽度不低于320
		if (iwidthSmall < 320)
		{
			iheightSmall = iheightSmall * (320/iwidthSmall);
			iwidthSmall = 320;
			
		}
        CGSize itemSizeSmall = CGSizeMake(iwidthSmall, iheightSmall);
        UIGraphicsBeginImageContext(itemSizeSmall);
        
        CGRect imageRectSmall = CGRectMake(0.0f, 0.0f, itemSizeSmall.width+2, itemSizeSmall.height+2);  //长和宽都增加2个像素，防止有些图片绘制旁边出现白线
		NSLog(@"before drawInRect!!,%f,%f",imageRectSmall.size.width,imageRectSmall.size.height);
        [image drawInRect:imageRectSmall];
		//NSLog(@"after drawInRect!!!!");
        UIImage *scaleImage = UIGraphicsGetImageFromCurrentImageContext();
		dataImage = UIImageJPEGRepresentation(scaleImage,0.38);
        
        //UIImagePNGRepresentation(scaleImage);// UIImageJPEGRepresentation(scaleImage,0.9);
		
    }else{
        dataImage = UIImageJPEGRepresentation(image,0.38);
    }
	NSLog(@"压缩bit 后：%ld",[dataImage length]/1024);
	return dataImage;
	
}

+(NSString*)getImageUrl:(NSString *)url witdh:(int)withd withtHeight:(int)height{
    
    NSString* phpAddress = @"http://www.dlb666.com/index.php/ImagesClass-setThumbs-url-";
    //php裁剪图片前缀   +url base64 编码  然后 -w-100-h-100 来设置图片尺寸
    
    //将图片URL地址 通过base64编码
    NSString* urlBase64 = [[url dataUsingEncoding:NSASCIIStringEncoding] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
    
    //按对应格式进行拼接
    NSString* imageUrl = [NSString stringWithFormat:@"%@%@-w-%d-h-%d",phpAddress,urlBase64,withd,height];
    return imageUrl;
    
}
//从时间中获取  小时和分钟
+(NSString*)getTimeFromTimeStr:(NSString*)timeStr{
    
    NSDate* compareDate =  [NSDate convertStringToDate:timeStr format:@"yyy-MM-dd HH:mm:ss"];
    //计算当前与当前时间差
    NSString* dateStr = [NSString stringWithFormat:@"%@",[NSDate date]];
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *nowDate = [format dateFromString:dateStr];
    
    if ([compareDate isEqualToDate:nowDate]) {
       
    }
    NSLog(@"compare %@    now :%@",compareDate,nowDate);

    
//    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd  HH:mm:ss"];
    NSDate *formatterDate = [inputFormatter dateFromString:timeStr];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"HH:mm"];
    NSString *newDateString = [outputFormatter stringFromDate:formatterDate];
    return  newDateString;
}
+(NSString*)getCurrentDateWithSystemLocalZone{
    
//    NSDate *date = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate: date];
//    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
//    NSDateFormatter* formatetter = [[NSDateFormatter alloc]init];
//    [formatetter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];

    return dateString;
    
  //  return [formatetter stringFromDate:localeDate];
    
}

+(BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    
    [comp1 month] == [comp2 month] &&
    
    [comp1 year]  == [comp2 year];
}



@end